package com.onec.service.route.controller;

import com.onec.service.route.dao.fluxe.BlockInfoFluxRepository;
import com.onec.service.route.entity.BlockInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.net.URI;

import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;

@Configuration
public class RouteFunctionConfig {


    @Autowired
    BlockInfoFluxRepository blockInfoFluxRepository;

    // 路由和路由结果：
    @Bean
    public RouterFunction<?> routeFunction() {
        return route(GET("rrrr/ttt"), this::record)
                .andRoute(POST("bbbb/nnn"), this::recordPost);
    }


    public Mono<ServerResponse> record(ServerRequest serverRequest) {
        return ServerResponse.ok().body(blockInfoFluxRepository.findAll().take(12), BlockInfo.class);
    }


    public Mono<ServerResponse> recordPost(ServerRequest serverRequest) {
        Mono<BlockInfo> blockInfoMono = serverRequest.bodyToMono(BlockInfo.class);
        //Mono<BlockInfo> saveBlock = blockInfoFluxRepository.save(blockInfoMono);
        ServerResponse.created(URI.create("https://www.baidu.com")).body(blockInfoMono, BlockInfo.class);
        return ServerResponse.ok().body(blockInfoFluxRepository.findAll().take(12), BlockInfo.class);
    }
}
